// cloudfunctions/login/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

// 核心逻辑 
exports.main = async (event) => {
  const wxContext = cloud.getWXContext();
  const db = cloud.database();
  const users = db.collection('users');
  const _ = db.command

  try {
    // 1. 用户信息兜底处理 
    const userData = event.userInfo || {
      nickName: "未授权用户",
      avatarUrl: ""
    };

    // 2. 数据库操作（增加事务锁）
    const {
      data
    } = await users.where({
      _openid: wxContext.OPENID,
      isDeleted: _.neq(true) // 数据库层面过滤已删除
    }).get();
    if (data.length === 0) {
      await users.add({
        data: {
          _openid: wxContext.OPENID,
          ...userData,
          createdTime: db.serverDate(),
          lastLogin: db.serverDate() // 新增字段跟踪活跃状态 
        }
      })
      // 这说明是新注册的用户
      return {
        code: 200,
        data: {
          openid: wxContext.OPENID,
          userInfo: userData,
          isLogin: false
        }
      };
    }
    // 走这里说明是已经登陆过的用户
    // 3. 标准化返回结构 
    return {
      code: 200,
      data: {
        openid: wxContext.OPENID,
        userInfo: userData,
        isLogin: true
      }
    };
  } catch (err) {
    // 4. 错误格式化 
    console.error('云函数错误:', err);
    return {
      code: 500,
      message: err.message
    };
  }
}